package com.goudan.rabbitmq.config;

import com.goudan.rabbitmq.constant.QueueDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @ClassName DirectModeConfig
 * @Description 直连模式配置
 * @Author lizejiao
 * @Date 2021年09月26日20:34:31
 **/
@Slf4j
@Configuration
public class DirectModeConfig {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 2.定义队列
     */
    @Bean
    public Queue directQueue() {
        return new Queue(QueueDefinition.LGD_DIRECT_QUEUE);
    }

    /**
     * 2.定义直连交换机
     */
    @Bean
    DirectExchange directExchange() {
        return new DirectExchange(QueueDefinition.LGD_DIRECT_EXCHANGE);
    }

    /**
     * 3.队列与交换机绑定
     */
    @Bean
    public Binding bindingDirectExchange(Queue directQueue, DirectExchange directExchange) {
        return BindingBuilder.bind(directQueue).to(directExchange).with(QueueDefinition.LGD_DIRECT_ROUTING_KEY);
    }

    /**
     * 声明错误队列
     */
    @Bean
    public Queue errorQueue() {
        return new Queue(QueueDefinition.LGD_ERROR_QUEUE);
    }

    /**
     * 声明错误交换机
     */
    @Bean
    DirectExchange errorExchange() {
        return new DirectExchange(QueueDefinition.LGD_ERROR_EXCHANGE);
    }


    @Bean
    public Binding errorBinding(Queue errorQueue, DirectExchange errorExchange) {
        return BindingBuilder.bind(errorQueue).to(errorExchange).with(QueueDefinition.LGD_DIRECT_ERROR_ROUTING_KEY);
    }

    @Bean
    public MessageRecoverer messageRecoverer() {
        return new RepublishMessageRecoverer(rabbitTemplate, QueueDefinition.LGD_ERROR_EXCHANGE, QueueDefinition.LGD_DIRECT_ERROR_ROUTING_KEY);
    }

}
